package springboot.springboot06_ssmp.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springboot.common_utils.R;
import springboot.springboot06_ssmp.entity.Contracts;
import springboot.springboot06_ssmp.mapper.ContractsMapper;
import springboot.springboot06_ssmp.service.IContractsService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author daiqiang
 * @since 2024-07-24
 */
@Slf4j
@CrossOrigin  //允许跨域
@RestController
@RequestMapping("contracts")
public class ContractsController {
    @Resource
    private IContractsService contractsService;
    @Resource
    private ContractsMapper contractsMapper;
    @RequestMapping("/getContracts")
    public R getAll(){
        return R.success(contractsService.list());
    }

    @PostMapping
    public R save(@RequestBody Contracts Contracts){
        boolean flag=contractsService.save(Contracts);
        if(flag) {
            return R.success("success");
        }else{
            return R.fail("fail");
        }
    }
    @PutMapping
    public  R update(@RequestBody Contracts contracts){

        return  R.success(contractsService.updateById(contracts));
    }
    @DeleteMapping("{id}")
    public  R delete(@PathVariable Integer id){
        return  R.success(contractsService.removeById(id));
    }
    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {

        return  R.success(contractsService.getById(id));
    }
    //条件查询
    @GetMapping("/list")
    public R<Map<String,Object>> getUserList(@RequestParam(value="contractName",required=false) String  contractName,
                                             @RequestParam (value="userId",required=false) Integer  userId,
                                             @RequestParam (value="pageNo",required=false) Long  pageNo,
                                             @RequestParam (value="pageSize",required=false) Long  pageSize
    ){
        LambdaQueryWrapper<Contracts> lqw = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(contractName)) {
            lqw.eq(Contracts::getContractName, contractName);
        }
          // 如果userId不为null，则添加查询条件（假设userId是Integer类型）
        if (userId != null) {
            lqw.eq(Contracts::getUserId, userId);
        }

        Page<Contracts> page = new Page<>(pageNo,pageSize);
        contractsMapper.selectPage(page,lqw);

        Map<String,Object> data = new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());
        return R.success(data);

    }

}
